package org.apache.servicecomb.samples.practise.houserush.login.service;

import com.auth0.jwt.exceptions.TokenExpiredException;
import org.apache.http.HttpStatus;
import org.apache.servicecomb.samples.practise.houserush.login.dao.UserDao;
import org.apache.servicecomb.samples.practise.houserush.login.entity.User;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public User createUser(User user) {
        User client = userDao.findByUsername(user.getUsername());
        if(client != null) {
            throw new InvocationException(HttpStatus.SC_BAD_REQUEST, "", "用户已经存在");
        } else {
            String s = user.makeHashedPassword(user.getPassword());
            user.setHashedPassword(s);
            return userDao.save(user);
        }

    }

    @Override
    public User findUser(int id) {
        return userDao.findOne(id);
    }

    @Override
    public void removeUser(int id) {
        userDao.delete(id);
    }

    @Override
    public boolean updatePassword(int id, String oldPassword, String newPassword) {
        User user = userDao.findOne(id);
        if(user == null) {
            throw new InvocationException(HttpStatus.SC_BAD_REQUEST, "","用户不存在");
        }
        if(!user.getHashedPassword().equals(user.makeHashedPassword(oldPassword))) {
            throw new InvocationException(HttpStatus.SC_BAD_REQUEST, "","密码错误");
        }
        user.setHashedPassword(user.makeHashedPassword(newPassword));
        userDao.save(user);
        return true;
    }

    @Override
    public User signin(User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        User u = userDao.findByUsername(username);
        if(u.getHashedPassword().equals(u.makeHashedPassword(password))) {
            u.generateToken();
            return u;
        }
        return null;
    }

    @Override
    public User verifyToken(String token) {
        int userId;

        try {
            userId = User.verifyTokenGetUserId(token);
        } catch (TokenExpiredException e) {
            throw new InvocationException(HttpStatus.SC_BAD_REQUEST,"","token过期");
        }catch (Exception e) {
            throw new InvocationException(HttpStatus.SC_BAD_REQUEST,"","token解析失败");
        }
        User user = userDao.findOne(userId);
        user.generateToken();
        return user;
    }
}
